package com.carepad.action.password;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.carepad.action.AbstractAction;
import com.carepad.entity.Users;
import com.carepad.service.PasswordChangeService;
import com.carepad.service.impl.UsersServiceImpl;
import com.carepad.util.EmailUtil;

public class PasswordChangeAction extends AbstractAction {

	private static final long serialVersionUID = 1L;

	private static Logger logger = Logger.getLogger(PasswordChangeAction.class);

	private Users Users;
	private String currentPassword;
	private String newPassword;
	private String confirmNewPassword;
	
	@Autowired protected PasswordChangeService passwordChangeService;
	
	@Autowired
	private UsersServiceImpl UsersServiceImpl;
	
	public String change() {
		return SUCCESS;
	}

	public String passwordChange() {
		try {

			validateEmail();
			if (hasErrors()) {
				return INPUT;
			}

			Users = passwordChangeService.currentUser(Users.getAccount());
			//Users = passwordChangeService.findByEmailAddress(Users.getEmail()).get(0);
			//Users = passwordChangeService.find
		/*	Users user = UsersServiceImpl.signIn(Users.getEmail(),
					currentPassword);
			*/
			if (Users == null) {
				addActionError(getText("system.user.signin.failed"));
				return INPUT;
			} else {
				if (currentPassword.equals(Users.getPassword())){
					if(newPassword.equals(confirmNewPassword))
						updatePassword(newPassword);
						return SUCCESS;
				}
				
				return INPUT;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			return SUCCESS;
		}
	}

	private void validateEmail() {
		if (Users.getAccount().isEmpty()) {
			addFieldError("Users.email", getText("system.user.email.empty"));
		}
		
		if(!(EmailUtil.chackEmailPattern(Users.getAccount()))) {
			addActionError(getText("error.email.invalid"));
		}
	}
		
	private void updatePassword(String newPassword){
		
		try {
			Users.setPassword(newPassword);
			passwordChangeService.saveNewPassword(Users,getSessionUserVariable().getUid());
			passwordChangeService.savePasswordHistory(Users,getSessionUserVariable().getUid());
			
		} catch (Exception e) {
			logger.error(e);
		}
		
	}

	public String getCurrentPassword() {
		return currentPassword;
	}

	public void setCurrentPassword(String currentPassword) {
		this.currentPassword = currentPassword;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public String getConfirmNewPassword() {
		return confirmNewPassword;
	}

	public void setConfirmNewPassword(String confirmNewPassword) {
		this.confirmNewPassword = confirmNewPassword;
	}

	public Users getUsers() {
		return Users;
	}

	public void setUsers(Users Users) {
		this.Users = Users;
	}
	
	
	
	
	
}
